const db = require('../../db/index');
const {UserModel} = require('../../model/UserSchema/User');
const mongoose = require('mongoose');


// 添加用户信息
exports.Add = function (arg) {
    return new Promise((resolve, reject) => {
        const userModel = new UserModel({
            Account: arg.Account,
            PassWord: arg.PassWord,
            Token: arg.Token,
            NickName: arg.NickName,
            Avatar: arg.Avatar,
            Introduce: arg.Introduce,
            sex: arg.sex,
            birth: arg.birth,
            RegisterTime: arg.RegisterTime,
            Region: arg.Region,
            LoginIp: arg.LoginIp,
            IsAbleUse: arg.IsAbleUse || true,
            RemainingLogins: arg.RemainingLogins,
            Identity: arg.Identity || "JobSeekers"
        })
        userModel.save((error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
};

/* 查询用户信息(只允许单条件查询)
        用户id,手机号,
* */
exports.Sel_singleArg = function (arg) {
    return new Promise((resolve, reject) => {
        UserModel.find({...arg}, (error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
};

// 查询文档中的对象/数组的属性
/*
*   @key           需要匹配的键名
*   @value         需要匹配的值
*   @filterOptions 需要过滤的属性
* */
exports.Sel_quoteType = function (key, value, filterOptions) {
    if(key==='_id') value = mongoose.Types.ObjectId(value); // 必须要将id转化为数据库的字符串
    return new Promise((resolve, reject) => {
        UserModel.aggregate([
            {$match: {[key]: value}},
            {$project: filterOptions}
        ]).exec((error, result) => {
            if (error) return reject(error)
            console.log({[key]: value}, result)
            resolve(result)
        });

        // UserModel.find({[key]: value}, filterOptions, (error, result) => {
        //     if (error) return reject(error)
        //     resolve(result)
        // })
    })
}

/* 查询用户信息(模糊/分页/多条件)
* */
exports.Sel = function (PageNumber,PageSize,arg) {
    return new Promise((resolve, reject) => {
        UserModel.find({...arg}).skip(PageNumber * PageSize).limit(PageSize).exec((error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
};
// 查询count
exports.Sel_Count = function (arg) {
    return new Promise((resolve, reject) => {
        UserModel.count({...arg}, (error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
}


// 修改信息
exports.Upd = function (_id, UpdateObject) {
    return new Promise((resolve, reject) => {
        UserModel.findByIdAndUpdate({_id}, UpdateObject, (error, result) => {
            if (error) return reject(error)
            resolve(result)
        })
    })
}
